"""
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-espnow-practice-simple
"""
import network
from machine import Pin
from utime import sleep_ms
from os import uname
from esp import espnow


class SimpleESPNow(object):
	IF_INDEX_STA = network.STA_IF
	IF_INDEX_AP = network.AP_IF
	BROADCAST_MAC = b'\xff\xff\xff\xff\xff\xff'

	def __init__(self):
		self.__espnow = None

		__is_esp32c3 = self.__is_esp32c3()
		self.__button_pin = 9 if __is_esp32c3 else 0
		self.__led_pin = 3 if __is_esp32c3 else 2

		self.__button = Pin(self.__button_pin, Pin.IN, Pin.PULL_UP)
		self.__button.irq(self.__button_callback, Pin.IRQ_RISING)
		self.__led = Pin(self.__led_pin, Pin.OUT, value=0)

	def __decode_mac_address(self, mac_address):
		if isinstance(mac_address, (bytes, bytearray)) and len(mac_address) == 6:
			return ":".join(['{:02x}'.format(byte) for byte in mac_address])
		else:
			return mac_address

	def __is_esp32c3(self):
		if uname()[0] == 'esp32':
			try:
				Pin(22, Pin.OUT)
				return False
			except ValueError:
				return True

	def __espnow_callback(self, espnow_instance):
		mac, message = espnow_instance.irecv(0)
		print(f'received from [{self.__decode_mac_address(mac)}], [message] {message}')

		if message == b'toggle_led':
			self.__led.value(not self.__led.value())

	def __button_callback(self, pin_instance:Pin):
		self.__espnow.send(SimpleESPNow.BROADCAST_MAC, b'toggle_led')

	def init_espnow(self):
		network.WLAN(network.AP_IF).active(True) # Or network.STA_IF

		self.__espnow = espnow.ESPNow()
		self.__espnow.deinit()

		self.__espnow.config(on_recv=self.__espnow_callback)
		self.__espnow.init()
		self.__espnow.add_peer(SimpleESPNow.BROADCAST_MAC, ifidx=SimpleESPNow.IF_INDEX_AP, encrypt=False)

		print('espnow is running...')


if __name__ == '__main__':
	station = network.WLAN(network.STA_IF)
	station.active(False)
	sleep_ms(500)
	station.active(True)

	simple = SimpleESPNow()
	simple.init_espnow()
